
<template>
    <el-drawer v-loading="drawerLoading" :model-value="modelValue" :close-on-click-modal="false" :size="600"
        class="repel-dialog" title="批量上传" :before-close="handleClose" @opened="handleOpen">
        <div class="my-form">
            <div class="upload">
                <div class="t form-item-title">刊播照片<i>*</i></div>
                <input class="real-upload-btn" :key="keyUploadNum" accept=".jpg" type='file' placeholder="" name="file"
                    webkitdirectory @change="onSelectDirectory($event)" @click="uploadPreClick">
                <button :class="{ disable: isUploading }" class="upload-batch"> <i class="upload-icon"></i>选择文件夹</button>
                <div class="tips">单次上传照片数量上限为500张，只支持jpg格式，单张照片大小不超过1M</div>
            </div>
            <!-- <el-button @click='browseFolder'>选择文件夹</el-button> -->
        </div>

        <div class="process" v-show="isUploading">照片上传进度：<i>{{ UploadResult.succssList.length }}</i>/{{
            XCUploader.totalNeedUpload }}</div>
        <div class="slider" v-show="isUploading">
            <el-slider v-model:model-value="showSliderValue" :max="1"></el-slider>
            <span>{{ (XCUploader.processInfo.percent * 100).toFixed(0) }}%</span>
        </div>

        <div class="result result-success" v-if="!isUploading && UploadResult.succssList.length > 0">
            <i class="iconfont icon-chenggong"></i>成功<span>{{ UploadResult.succssList.length }}张</span>
        </div>
        <div class="result result-process" v-if="isUploading">
            <i class="iconfont icon-tishi1"></i><span>温馨提示：请勿关闭界面,否则将终止文件上传</span>
        </div>
        <div class="result result-error" v-if="!isUploading && UploadResult.errorList.length > 0">
            <i class="iconfont icon-shibai"></i>失败<span>{{ UploadResult.errorList.length }}张</span>
            <a @click="genErrorInfo" href="javascript:;">导出失败信息</a>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button :disabled="isUploading" type="primary" class="cancel" @click="handleClose"> 关 闭 </el-button>
            </div>
        </template>


        <el-dialog title="提示信息" :model-value="dailogTipsShow" width="480px">
            <ul>
                <li v-for="item in errorList" :key="item">{{ item }}</li>
            </ul>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="dailogTipsShow = false"> 确定 </el-button>
                </span>
            </template>
        </el-dialog>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted } from 'vue';
import _XCUploader, { OBSResultInfo } from '@/utils/XCUpLoader';
import XCMessageMgr from '@/utils/XCMessageMgr';
import { uploadPhotoBatch, uploadPhotoBatchError } from '@/api/plan';

const XCUploader = new _XCUploader();
const emits = defineEmits<{ (e: 'update:modelValue', visible: boolean): void; (e: 'success'): void }>();
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    selectRow: {
        type: Object,
        default: () => {},
    },
});

const drawerLoading = ref(false);

const handleClose = () => {
    if (!isUploading.value) {
        resetXCupload();
        emits('update:modelValue', false);
        return;
    }

    XCMessageMgr.Instance.showConfirm('关闭界面会导致文件上传失败,是否继续?', (ok) => {
        if (ok) {
            resetXCupload();
            emits('update:modelValue', false);
            XCUploader.stopUpload();
        }
    })

};

function resetXCupload() {
    XCUploader.reset();
    UploadResult.value = XCUploader.UploadResult;
    showSliderValue.value = 0;
}
const handleOpen = () => {
    resetXCupload();
};


onMounted(() => {

});


const dailogTipsShow = ref(false);
const keyUploadNum = ref(0)
function showErrorTips(errlist: string[]) {
    if (!errlist.length) return;
    errorList.value = errlist;
    dailogTipsShow.value = true;
    keyUploadNum.value++;
}
const errorList = ref<string[]>([]);
const isUploading = ref(false);
function uploadPreClick(e: any) {
    if (isUploading.value) {
        e.preventDefault();
    }
}



const UploadResult = ref(XCUploader.UploadResult);
const onSelectDirectory = (e: any) => {
   
    console.log("files:", e.target.files);
    const files = [...e.target.files];
    if (files.length > 500) {
        showErrorTips(['文件数量不能超过500个']);
        return;
    }
    let errList: string[] = [];
    files.forEach(file => {
        if (file.size > 1024 * 1024) {
            errList.push(file.name + ' 大于1M请重新检查后上传');
        }
        if (!(file.type as string).includes('jpg') && !(file.type as string).includes('jpeg')) {
            errList.push(file.name + ' 格式不为jpg');
        }

    });
    if (errList.length) {
        showErrorTips(errList);
        return;
    }

    async function uploadToXC(obsRes: OBSResultInfo) {
        const result: { isSuccess: boolean, error: string } = {
            isSuccess: false,
            error: ''
        };
        isUploading.value = true;
        try {
            const res = await uploadPhotoBatch({
                batchId:props.selectRow.batchId,
                image: {
                    fileId: obsRes.fileId,
                    imgName: obsRes.fileName,
                    imgPath: obsRes.resUrl,
                }
            });
            console.log('res', res);
            if (res.success) {
                result.isSuccess = true;
            }
            else {
                result.isSuccess = false;
                result.error = res.errorMessage + '';
            }

        } catch (error: any) {
            result.isSuccess = false;
            result.error = error.msg;
        }
        return result;
    }
    XCUploader.reset();
    XCUploader.startUploadTask(files, uploadToXC, () => {
        isUploading.value = false;
        keyUploadNum.value++; //上传完之后 强制重载input
    }, () => {
        showSliderValue.value = XCUploader.processInfo.percent;
        console.log('percent', showSliderValue.value);
        UploadResult.value = XCUploader.UploadResult;
    });

}
const showSliderValue = ref<number | undefined>(0);


async function genErrorInfo() {
    const errorList = XCUploader.UploadResult.errorList;
    // let str = `文件名，失败原因\n`;
    // for (let i = 0; i < errorList.length; i++) {
    //     str += `${errorList[i].fileName + '\t'},`;
    //     str += `${errorList[i].errorDes + '\t'},`;
    //     str += '\n';
    // }
    // // encodeURIComponent解决中文乱码
    // const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    // // 通过创建a标签实现
    // const link = document.createElement("a");
    // link.href = uri;
    // // 对下载的文件命名
    // link.download = "批量上传错误信息.csv";
    // link.click();
    const errorInfoList = errorList.map((item) => {
        return {
            photoName: item.fileName,
            errorInfo: item.errorDes
        }
    })

    const errUrl = await uploadPhotoBatchError({ errorInfoList })
    console.log('errUrl', errUrl);
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = errUrl;
    link.setAttribute('download', '上传错误信息');
    // document.body.appendChild(link);
    link.click(); // 强制触发a标签事件
}

//这种只在第一次弹出安全访问提示
async function browseFolder() {
    window.confirm = ()=>{
        return true;
    }
    const files = [];
    const dirHandle = await showDirectoryPicker();
    console.log('dirHandle', dirHandle);
    for await (const entry of dirHandle.values()) {
        if (entry.kind === "file") {
            const file = await entry.getFile();
            files.push(file);
        }
    }
    console.log('files',files);
}

</script>

<style lang="scss" scoped>
.form-item-title {
    width: 260px;
    display: flex;
    align-items: center;
    height: 30px;
    font-size: 14px;

    i {
        display: inline-block;
        color: #F00000;
        margin-top: 3px;
        margin-left: 2px;
    }
}

.el-form-item {
    width: 260px;
    // background-color: pink;
    margin: 0;
}

.el-form-item:nth-child(2n+1) {
    margin-right: 20px;
}

::v-deep .el-input {
    display: inline-block;
    width: 260px !important;
}

::v-deep .el-slider__button-wrapper {
    opacity: 0;
    pointer-events: none;
}

::v-deep .el-slider__bar {
    background-color: #E60044;
}

::v-deep .el-slider__runway {
    pointer-events: none;
}

.upload {
    margin-top: -5px;

    .t {
        margin-bottom: 5px;
    }
}

.my-form {
    // margin-top: -30px;
}

.disable.upload-batch {
    opacity: 0.6;
}

.upload-batch {
    position: relative;
    left: -125px;
    cursor: pointer;
    pointer-events: none;
    border: 0;
    width: 124px;
    height: 32px;
    background-color: #E60044;
    border-radius: 4px;
    text-align: center;
    line-height: 32px;
    color: #fff;

    i {
        width: 12px;
        height: 12px;
        background: url(@/assets/upload.png) no-repeat;
        background-size: 12px 12px;
        vertical-align: middle;
    }
}

.upload-icon {
    display: inline-block;
    width: 12px;
    height: 12px;
    background-color: pink;
    background: url(@/assets/upload.png) no-repeat center;
    background-size: 12px 12px;
    vertical-align: middle;
    margin-right: 5px;
    margin-top: -4px;
}

.process {
    margin-top: 10px;

    i {
        font-size: 18px;
        font-style: normal;
        font-weight: 600;

    }
}

.slider {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    span {
        margin-left: 2px;
        margin-top: -1px;
    }
}

.result {
    margin-top: 10px;
    width: 546px;
    height: 42px;
    line-height: 35px;
    border-radius: 4px;
    padding: 5px;
    padding-left: 12px;
}

.result-success {
    background-color: rgb(232, 246, 237);
    color: #000;

    span {
        color: #22AC4E;
    }

    i {
        color: #22AC4E;
        margin-right: 8px;
    }
}

.result-error {
    background-color: rgb(255, 238, 236);

    a {
        float: right;
        text-decoration: none;
        color: #4D88FF;
    }

    span {
        color: #E60044;
        margin-left: 2px;
    }

    i {
        color: #F15A4A;
        margin-right: 8px;
    }
}

.result-process {

    background-color: rgb(255, 247, 231);
    color: #666666;

    i {
        color: #FFB414;
        margin-right: 8px;
    }
}

.real-upload-btn {
    opacity: 0;
    width: 124px;
}

.tips {
    font-size: 12px;
    color: #999999;
    text-align: left;
    line-height: 30px;
}
</style>
@/utils/XCUpLoader